package com.finesys.backend.api.controller.base;

import javax.servlet.http.HttpServletRequest;

import com.finesys.backend.common.utils.Const;
import com.finesys.backend.common.utils.HttpStatusCodes;
import com.finesys.backend.common.utils.JacksonMapper;
import com.finesys.backend.common.utils.JsonResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class BaseController {
	private JacksonMapper mapper = new JacksonMapper("yyyy-MM-dd HH:mm:ss");

	/**
	 * 返回成功消息
	 * @param message
	 * @return
	 */
	public String renderSuccessJson(String message) {
		return renderJson(HttpStatusCodes.OK, message);
	}

	/**
	 * 返回成功消息
	 * @param message
	 * @param object
	 * @return
	 */
	public String renderSuccessJson(String message, Object object) {
		return renderJson(HttpStatusCodes.OK, message, object);
	}

	public String renderErrorJson(int code, String message) {
		return renderJson(code, message);
	}

	/**
	 * 返回消息
	 * @param code
	 * @param message
	 * @return
	 */
	public String renderJson(int code, String message) {
		return mapper.toJson(new JsonResult(code, message));
	}

	/**
	 * 返回消息
	 * @param code
	 * @param message
	 * @param object
	 * @return
	 */
	public String renderJson(int code, String message, Object object) {
		return mapper.toJson(new JsonResult(code, message, object));
	}

	/**
	 * 从request上获取access token
	 * @return
	 */
	public String getAccessToken() {
		HttpServletRequest request = getRequest();
		return request.getHeader(Const.ACCESS_TOKEN_KEY);
	}

	/**
	 * 获取客户端ip地址
	 * @return
	 */
	public String getRemoteAddress() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 从request上获取fresh token
	 * @return
	 */
	public String getFreshToken() {
		HttpServletRequest request = getRequest();
		return request.getHeader(Const.FRESH_TOKEN_KEY);
	}

	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
}
